package com.yunlongn.async.content;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 线程池命名工厂
 * @author yunlongn
 */
public class NameThreadFactory implements ThreadFactory {

    private final AtomicLong index = new AtomicLong(0);
    private final String threadNamePrefix;

    /**
     * 当java虚拟机中没有非守护线程在运行的时候，java虚拟机会关闭。
     * 当所有常规线程运行完毕以后，守护线程不管运行到哪里，虚拟机都会退出运行。
     * 所以你的守护线程最好不要写一些会影响程序的业务逻辑。否则无法预料程序到底 会出现什么问题。
     */
    private final boolean daemon;

    public NameThreadFactory(String threadNamePrefix, boolean daemon) {
        this.threadNamePrefix = threadNamePrefix;
        this.daemon = daemon;
    }

    @Override
    public Thread newThread(Runnable runnable) {
        Thread thread = new Thread(runnable, threadNamePrefix + index.getAndIncrement());
        thread.setDaemon(daemon);
        if (thread.getPriority() != Thread.NORM_PRIORITY) {
            thread.setPriority(Thread.NORM_PRIORITY);
        }
        return thread;
    }
}
